package cn.sxt.common.shop.util;

import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;
@Component("encrptUtil")
public class EncrptUtil {

	/**
	 * 加密
	 */
	public String encode(String souStr){
		/* 获取随机数 */
		String randStr = this.randStr(32);
		/* 将密码使用sha256加密 */
		String jiami = DigestUtils.sha256Hex(souStr + randStr);
		/* 加密算法 */
		String enType = "sha256";
		/* 分隔符 */
		String split = "$";
		return enType + split + randStr + split + jiami;
	}
	
	/**
	 * 解密
	 */
	public boolean decode(String encode,String pass){
		/* 加密算法 */
		String enType = "sha256";
		/* 分隔符 */
		String split = "$";
		String[] encodes = encode.split("\\"+split);
		String randStr = encodes[1];
		String jiami = DigestUtils.sha256Hex(pass + randStr);
		String decode = enType + split + randStr + split + jiami;
		return encode.equals(decode);
	}
	
	/**
	 * 生成随机数
	 */
	public String randStr(int length){
		StringBuffer  str = new StringBuffer();
		String allStr = ConstantFinalUtil.ALLSTR;
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			int randInt = random.nextInt(allStr.length());
			char ch = allStr.charAt(randInt);
			str.append(ch);
		}
		return str.toString();
	}
	
	public static void main(String[] args) {
		EncrptUtil encrptUtil = new EncrptUtil();
		/*String randStr = encrptUtil.randStr(32);*/
		String password = "111111";
		String encode = encrptUtil.encode(password);
		System.out.println(encode);
		boolean flag = encrptUtil.decode(encode, password);
		System.out.println(flag);

	}
}
